import Vue 			from 'vue'
import util 		from '../../util'
import axios 		from 'axios'
import { Dialog,Toast } from 'vant';
Vue.use(Dialog,Toast);

export default {
	name: 'sell',
	data(){
		return {
			type:1,			//付款方式  1:支付宝  2:银行卡   3:微信
			name:'',		//出售币种名称
			account:0,		//数量
			allPrice:0,		//总价
			logo:'',		//当前页面logo
			dialogBox:false,//是否显示发送验证页面
			loading:false,	//按钮是否加载中
			mobile:'',		//用户手机号码
			randCode:'',	//验证码
			btnBgColor:'rgba(211,220,230,1)',	//提交验证码按钮颜色
			btnStatus:1,	//发送验证码按钮状态   1:可发送   2:加载中   3:发送成功(倒计时)
			leftSec:60,		//倒计时剩余时间
			ETHAccount:'',	//用户ETH账户地址
			EOSAccount:'',	//用户EOS账户地址
			error:false,
			uploadTimes:0,	//重复提交次数
			orderId:'',		//mykey中从sellType页面携带过来的订单编号
		}
	},
	watch:{
		randCode:{
			handler(newVal,oldVal){
				if(newVal && newVal.length > 4){
					this.randCode = newVal.slice(0,4);
				}
				this.btnBgColor = newVal?'#1C4D7F':'rgba(211,220,230,1)';
			},
			immediate:true
		}
	},
	methods:{
		upload(){
			//售出
			if(!this.randCode) return
			this.loading = true;
			let params = {
				token:this.token || util.getToken(),
				currency_id:this.name,		//币种
				number:this.account,		//数量
				account_id:this.accountId,	//收款ID
				captcha:this.randCode	//验证码
			}
			util.fetch(`${util.ajaxUrl}/otc/outmoney-new`,params).then(res => {
				this.dialogBox = false;
				Toast(res.retMsg || '未知错误');
				if(res.retCode === 0){
					setTimeout(()=>{
						this.$router.replace({
							path:'/orderDetail',
							query:{
								id:res.retData.id,
								pageState:2,
								death:1
							}
						})
					},1500)
				}else if(res.retCode == 100001){
					this.randCode = '';
					this.dialogBox = true;
				}else{
					setTimeout(() => {
						this.leftSec = 60;
						this.btnStatus = 1;
						this.randCode = 0;
						this.loading = false;
						this.goBack('special');
					},1500)
				}
			}).catch(error => {
				console.log(error)
			}).finally(() => {
				setTimeout(()=>{
					this.loading = false;
				},500)
			})
		},
		sendRandCode(){
			//发送验证码
			if(!this.mobile){
				Toast('手机号码获取失败');
				return
			}
			if(this.btnStatus===1){
				this.btnStatus = 2;
				util.fetch(`${util.ajaxUrl}/site/send-sms`,{
					token:this.token || util.getToken(),
					mobile:this.mobile,
					type:'draw'
				}).then(res => {
					Toast.clear();
					if(res.retCode === 0){
						// Toast('发送成功');
						this.btnStatus = 3;
						this.timer(this.leftSec);
					}else{
						this.btnStatus = 1;
						Toast(res.retMsg || '未知错误')
					}
				}).catch(error => {
					this.btnStatus = 1;
					console.log(error)
				})
			}
		},
		isOtcOutmoeny(){
			//判断是否有出售中的订单
			return new Promise(resolve => {
				Toast.loading({
					message: '加载中...',
					duration:0,
					forbidClick: true
				});
				util.fetch(`${util.ajaxUrl}/mykey/is-otc-outmoeny`,{
					token:this.token || util.getToken(),
				}).then(res => {
					if(res.retCode == 0){
						if(res.retData && res.retData.id){
							resolve(res.retData.id)
						}else{
							resolve('')
						}
					}else{
						resolve('')
						Toast(res.retMsg || '未知错误')
					}
				})
			})
		},
		goSell(){
			let self = this;
			this.isOtcOutmoeny().then(orderId => {
				if(orderId){
					Toast.clear();
					//有出售中的订单，不能继续
					Dialog.confirm({
						title: '您有一笔出售订单未完成',
						message: '请先完成此订单交易',
						className:'sellType-dialog',
						cancelButtonColor:'#1989fa',
						confirmButtonText:'进入订单',
						cancelButtonText:'取消',
						overlayClass:'sellType-mark'
					}).then(() => {
						//获取订单状态
						util.fetch(`${util.ajaxUrl}/mykey/otc-outmoney-detail`,{
							token:self.token || util.getToken(),
							id:orderId
						}).then(res => {
							if(res.retCode == 0){
								if(res.retData.state && res.retData.state==-5){
									self.$router.replace({
										path:'/makeOrder',
										query:{
											death:1,
											orderId:orderId,
											isSell:1
										}
									})
								}else{
									self.$router.replace({
										path:'/orderDetail',
										query:{
											death:1,
											pageState:2,
											id:orderId
										}
									})
								}
							}else{
								Toast(res.retMsg || '未知错误')
							}
						})
						console.log('confirm')
					}).catch(() => {
						console.log('cancel')
					})
				}else{
					Toast.clear();
					util.checkDialog().then(confirm => {
						this.dialogBox = true
					},cancel => {
						
					})
				}
			})
		},
		timer(){
			//倒计时
			if(this.leftSec <= 0){
				this.leftSec   = 60;
				this.btnStatus = 1;
			}else{
				this.leftSec--;
				this.btnStatus = 3;
				setTimeout(this.timer,1000)
			}
		},
		editPayType(){
			//修改支付信息
			util.callHandler('openUrl',{
				url:'bbjApp://openPayments',
				title:'',
				needLogin:true,
				popVC:true,		//跳转的时候是否干掉当前页面
				hiddenNav:true,	//是否全屏
			},res => {
				console.log(res)
			})
			setTimeout(() => {
				Toast('请升级到最新版本app')
			},1500)
			// this.$router.push({
			// 	path:'/setUserDropInfo',
			// 	query:{
			// 		type:this.type,
			// 		edit:1
			// 	}
			// })
		},
		goBack(special){
			util.navigateBack(-1,this,special)
			// this.$router.go(-1)
		},
		closeBox(){
			this.dialogBox = false;
		},
		blur(){
			window.scrollTo(0, 0);
		},
		init(){
			//获取实时价格
			util.getPriceByName(this.name,2,this.account).then(price => {
				this.allPrice = util.accMul(this.account,price).toFixed(2)
			}).catch(() => {
				Toast('获取实时单价失败')
			})
			setTimeout(() => {
				this.init();
			},util.time)
		},
		getPhone(){
			//拉取手机号码
			util.fetch(`${util.ajaxUrl}/user/verified-info`,{
				token:this.token || util.getToken()
			}).then(res => {
				if(res.retCode === 0){
					this.mobile = res.retData.phone || res.retData.email;
				}else{
					Toast(res.retMsg || '未知错误')
				}
			}).catch(error => {
				console.log(error)
			})
		}
	},
	created() {
		let _query 	    = this.$route.query;
		this.type 	    = _query.type;
		this.name 	    = _query.name;
		this.account    = _query.account;
		this.accountId  = _query.accountId;
		this.orderId    = _query.orderId;
		if(!sessionStorage.getItem('refresh') && _query.name === 'EOS'){
			window.location.reload();
			sessionStorage.setItem('refresh',1)
		}
		//从缓存中找icon
		let otcConfig = util.getStorage('otcConfig');
		if(otcConfig){
			otcConfig = JSON.parse(otcConfig);
			this.logo = otcConfig.currency[this.name].logo;
		}
		util.waitSDKReady().then(token => {
			this.token = token;
			this.init();
			this.getPhone();
		}).catch((e) => {
			Toast('获取token失败')
		})
		setTimeout(() => {
			//退出登录的时候native调用H5方法清除token缓存
			util.registerHandler('loginOutDeleteToken',res => {
				window.token = '';
				this.token = '';
				localStorage.removeItem('token');
			})
			util.callHandler('setStatusBarStyle',{
				style:'dark'
			})
		},500)
    }
}